package cn.shequren.communityPeople.pay.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.paysdk.R;

import java.net.URLDecoder;

import cn.shequren.communityPeople.pay.bean.AliPayResult;
import cn.shequren.communityPeople.pay.bean.PayEvent;
import cn.shequren.communityPeople.pay.constants.CommUnityPayConstants;
import cn.shequren.communityPeople.pay.utils.WXPayUtil;

/**
 * Created by Tony.Fan on 2018/3/16 10:46
 */
public class CommUnityPayActivity extends Activity {

    private boolean isWeixinPaid = false;

    private WeiXinPayResultReceiver weiXinPayResultReceiver;
    private String curPayMethed = "";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    //支付宝支付成功回调
                    AliPayResult payResult = new AliPayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    String resultMessage = payResult.getMemo();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK,
                                CommUnityPayConstants.PAY_RESULT_SUCCESS);
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK,
                                CommUnityPayConstants.PAY_RESULT_ERROR);
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK,
                                CommUnityPayConstants.PAY_RESULT_ERROR);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.payWindowTransparent);
        isWeixinPaid = false;
        Intent intent = getIntent();
        String payMethod = intent.getStringExtra("PAY_METHOD");
        String payMedium = intent.getStringExtra("PAY_MEDIUM");
        String payInfo = intent.getStringExtra("PAY_INFO");
        curPayMethed = payMethod;
        callPay(payMethod, payMedium, payInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CommUnityPayConstants.REQUEST_CODE_SUCCESS) {
            //支付回调
            String payResult = data.getStringExtra("pay_result");
            int payResultCode = CommUnityPayConstants.PAY_RESULT_ERROR;
            if (payResult == null || payResult.equals("fail")) {
                payResultCode = CommUnityPayConstants.PAY_RESULT_ERROR;
            } else if (payResult.equals("cancel")) {
                payResultCode = CommUnityPayConstants.PAY_RESULT_CANCEL;
            } else if (payResult.equals("success")) {
                payResultCode = CommUnityPayConstants.PAY_RESULT_SUCCESS;
            }
            onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_UNIONPAY, payResultCode);
        }
    }

    /**
     * 调用支付方式
     *
     * @param payMethod
     * @param payMedium
     * @param payInfo
     */
    private void callPay(String payMethod, String payMedium, String payInfo) {
        try {
            // 支付宝插件支付
            if ((CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK.equals(payMethod)) && "app".equals(payMedium)) {
                final String finalpayInfo = payInfo;
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        //支付成功回调参数
                        PayTask alipay = new PayTask(CommUnityPayActivity.this);
                        // 调用支付接口
                        String result = alipay.pay(finalpayInfo, true);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = result;
                        handler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (CommUnityPayConstants.PAY_METHOD_WECHAT.equals(payMethod) && "app".equals(payMedium)) {
                WXPayUtil wxPay = new WXPayUtil(this);
                // 微信支付
                if (wxPay.isWxInstalledAndSurported()) {
                    weiXinPayResultReceiver = new WeiXinPayResultReceiver();
                    registerReceiver(weiXinPayResultReceiver, new IntentFilter(
                            CommUnityPayConstants.WEIXIN_PAY_INTENT_ACTION));
                    wxPay.sendPayReq(URLDecoder.decode(payInfo, "utf-8"));
                } else {
                    WpToast.l(this, "未检测到微信客户端");
                    finish();
                }
            }
        } catch (Exception e) {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isWeixinPaid && CommUnityPayConstants.PAY_METHOD_WECHAT.equals(curPayMethed)) {
            onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_WECHAT, CommUnityPayConstants.PAY_RESULT_CANCEL);
        } else {
            isWeixinPaid = true;
        }
    }

    private class WeiXinPayResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            onPayCallback(RESULT_OK, CommUnityPayConstants.PAY_METHOD_WECHAT,
                    intent.getIntExtra("payResult", CommUnityPayConstants.PAY_RESULT_ERROR));
        }
    }

    /**
     * 支付结果回调
     *
     * @param resultCode
     * @param payMethod
     * @param payResult
     */
    private void onPayCallback(int resultCode, String payMethod, int payResult) {
        String msg = "";
        if (payResult == CommUnityPayConstants.PAY_RESULT_SUCCESS) {
            msg = "支付成功";
        } else if (payResult == CommUnityPayConstants.PAY_RESULT_CANCEL) {
            msg = "取消支付";
        } else if (payResult == CommUnityPayConstants.PAY_RESULT_ERROR) {
            msg = "支付失败";
        }
        WpToast.l(this, msg);
        payRxBus(resultCode, payMethod, payResult);
    }

    /**
     * 支付通知
     *
     * @param resultCode
     * @param payMethod
     * @param payResult
     */
    private void payRxBus(int resultCode, String payMethod, int payResult) {
        PayEvent payEvent = new PayEvent();
        payEvent.setResultCode(resultCode);
        payEvent.setPayMethod(payMethod);
        payEvent.setPayResult(payResult);
        RxBus.getInstance().post(payEvent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (weiXinPayResultReceiver != null) {
            unregisterReceiver(weiXinPayResultReceiver);
            weiXinPayResultReceiver = null;
        }
    }
}
